import React, { createRef, Component } from 'react'
import BetterScroll from 'better-scroll'
import bsStyle from './style.module.css'

class MyScroll extends Component {
  constructor(props) {
    super(props)
    this.myRef = createRef()
  }

  componentDidUpdate() {
    console.log(this.props, '接收update')
    if (this.props.flag) {
      this.bsFunc()
    }
  }

  bsFunc = () => {
    const { handlePullingDown, handlePullingUp } = this.props
    this.bs = new BetterScroll(this.myRef.current, {
      // 开启 下拉
      pullDownRefresh: {
        threshold: 50, // 阀值
        stop: 20,
      },
      // 开启 上拉
      pullUpLoad: {
        threshold: -50,
      },
    })

    // 监听事件
    this.bs.on('pullingDown', () => {
      console.log('下拉')
      // 子父 传参
      handlePullingDown &&
        handlePullingDown((res) => {
          this.bs.finishPullDown()
          // this.bs.refresh()
        })
    })

    this.bs.on('pullingUp', () => {
      console.log('上拉')
      handlePullingUp &&
        handlePullingUp((res) => {
          // console.log('子组件:', res)
          this.bs.finishPullUp()
          // this.bs.refresh()
        })
    })
  }

  // 防止内存泄漏操作
  componentWillUnmount() {
    this.bs = null
  }

  render() {
    return (
      <div ref={this.myRef} className={bsStyle['bs-wrapper']}>
        <div className={bsStyle['bs-content']}>{this.props.children}</div>
      </div>
    )
  }
}

export default MyScroll
